package com.xdf.whiteaccount.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.ClassicConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;

/**
 * @program: white-account
 * @description: flyway配置
 * @author: 张柯
 * @create: 2021-06-15 09:21
 **/
@Slf4j
@Component
public class FlywayConfig {
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    @Autowired
    public void setDataSource(@Qualifier("dataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 数据库版本更新
     */
    public void migrate() {
        ClassicConfiguration configuration = new ClassicConfiguration();
        configuration.setDataSource(dataSource);
        configuration.setLocationsAsStrings("db/migration");
        configuration.setEncodingAsString("UTF-8");
        configuration.setOutOfOrder(true);
        configuration.setBaselineOnMigrate(true);
        configuration.setCleanDisabled(true);
        configuration.setIgnoreMissingMigrations(true);
        Flyway flyway = new Flyway(configuration);
        try {
            flyway.migrate();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            log.error("数据库版本更新失败!");
        }
    }
}
